package main

import (
	"fmt"
	"github.com/go-redis/redis"
	"sync"
	"time"
)

const (
	KEY_PREFIX = "auth_cookie_"
)

var (
	blog_redis      *redis.Client
	blog_redis_once sync.Once
)

func createRedisClient(address, password string, db int) *redis.Client {
	client := redis.NewClient(&redis.Options{
		Addr:     address,
		Password: password,
		DB:       db,
	})
	if err := client.Ping().Err(); err != nil {
		panic(fmt.Errorf("conncet to redis %d failed: %v", db, err))
	} else {
		fmt.Println("conncet to redis db: ", db)
	}
	return client
}

func GetRedisClient() *redis.Client {
	blog_redis_once.Do(func() {
		if blog_redis == nil {
			blog_redis = createRedisClient("127.0.0.1:6379", "", 0)
		}
	})
	return blog_redis
}

func SetCookieAuth(cookieValue, uid string) {
	client := GetRedisClient()
	if err := client.Set(KEY_PREFIX+cookieValue, uid, time.Hour*24*3).Err(); err != nil {
		fmt.Printf("write pair(%s, %s) to redis failed: %v\n",
			cookieValue, uid, err)
	} else {
		fmt.Printf("write pair(%s, %s) to redis\n",
			cookieValue, uid)
	}
}

// 根据cookie获取uid
func GetCookieAuth(cookieValue string) string {
	client := GetRedisClient()
	uid, err := client.Get(KEY_PREFIX + cookieValue).Result()
	if err != nil {
		if err != redis.Nil {
			fmt.Printf("get auth info %s failed: %v\n", cookieValue, err)
		}
	}
	return uid
}
